package binarycrew.livewallpapers.wallpapers;

import android.graphics.*;
import android.util.Log;
import binarycrew.livewallpapers.Preferences;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class PhotoLiveWallpaper extends ALiveWallpaper {

	private static final String TAG = "PhotoLiveWallpaper";
	Bitmap mIcon = null;

	public PhotoLiveWallpaper() {
		this.code = "photo_wallpaper";
	}

	@Override
	public String getName() {
		return "Sample Photo wallpaper #1";
	}

	@Override
	public String getDescription() {
		return "Example Photo wallpaper #1";
	}

	@Override
	public Double getFPS() {
		return 0.1;
	}

	@Override
	public void create() {
	}

	@Override
	public void destroy() {
	}

	long mLastUpdate = -1;
	private Bitmap bm;
	private double offset = 0.5;
	private int offset_max;

	@Override
	public void drawCanvas(Canvas canvas) {
		if (!isInitialised)
			return;

		if (mLastUpdate == -1 || System.currentTimeMillis() - mLastUpdate > 10000) {
			Log.d("WALLPAPER", "t: " + mLastUpdate);
			mLastUpdate = System.currentTimeMillis();

			File f = selectNewPhoto();
			bm = scalePhoto(f);

            if(bm != null)
			    canvas.drawBitmap(bm, (int) (offset_max * offset), 0, null);

			drawPhotoSource(canvas);
		}
	}

	private void drawPhotoSource(Canvas canvas) {
		int fontSize = 20;

		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		paint.setStyle(Paint.Style.FILL);
		paint.setColor(Color.WHITE);
		paint.setTextSize(fontSize);

		Paint paintBox = new Paint();
		paintBox.setStyle(Paint.Style.FILL);
		paintBox.setColor(Color.BLACK);
		paintBox.setAlpha(90);

		String s = "Zdroj: SME.SK";
		int px = getWidth() - (int) (paint.measureText(s) * 1.1);
		int py = (int) (getHeight() * 0.08);

		canvas.drawRect(px - 5, py - fontSize - 5, getWidth() - 5, py + fontSize - 5, paintBox);
		canvas.drawText(s, px, py, paint);
	}

	private Bitmap scalePhoto(File f) {
        if(f == null) return null;

		FileInputStream fis;
		Bitmap bitmap = null;
		try {

			fis = new FileInputStream(f);

			BitmapFactory.Options opt = new BitmapFactory.Options();
			bitmap = BitmapFactory.decodeStream(fis, null, opt);
			if (bitmap == null)
				bitmap = loadDefaultImage();

			double scale = 1;
			if (opt.outHeight != -1)
				scale = (getHeight()) / (double) opt.outHeight;

			bitmap =
					Bitmap.createScaledBitmap(bitmap, (int) (opt.outWidth * scale), (int) (opt.outHeight * scale), true);
			fis.close();

			int real_width = (int) (opt.outWidth * scale);
			offset_max = -(real_width - getWidth());
		}
		catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bitmap;
	}

	private final Set<String> recentPhotos = new HashSet<String>();

	private File selectNewPhoto() {
		File f;
		String[] files = Preferences.getFilesDir().list();
		if (files.length == 0)
			return null;

		while (true) {

			//Reset after we have shown at least half of the photos
			if (files.length < recentPhotos.size() * 2)
				recentPhotos.clear();

			int pos = (int) (Math.random() * files.length);
			f = new File(Preferences.getFilesDir(), files[pos]);
			if (!f.getName().equals(Preferences.DEFAULT_IMAGE)) {
				if (recentPhotos.contains(f.getName())) {
					Log.d(TAG, "already shown: " + f.getName());
					continue;
				}
				else {
					recentPhotos.add(f.getName());
					Log.d(TAG, "select: " + f.getName());
					break;
				}
			}
			else {
				if (files.length == 1)
					break;
			}

		}

		return f;
	}

	private Bitmap loadDefaultImage() throws FileNotFoundException {
		File f = new File(Preferences.getFilesDir(), Preferences.DEFAULT_IMAGE);

		FileInputStream fis;

		fis = new FileInputStream(f);
		BitmapFactory.Options opt = new BitmapFactory.Options();
		bm = BitmapFactory.decodeStream(fis, null, opt);

		return bm;
	}

	@Override
	public void drawCanvasOnOffsetsChanged(
			Canvas c,
			float xOffset,
			float yOffset,
			float xStep,
			float yStep,
			int xPixels,
			int yPixels
			) {
		offset = xOffset;
        if(bm != null)
		    c.drawBitmap(bm, (int) (offset_max * xOffset), 0, null);
		drawPhotoSource(c);
	}
}
